package gsi

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	"runtime"
	"strings"
)

// CPU information.
type CPU struct {
	Vendor  string `json:"vendor"`
	Model   string `json:"model"`
	Cpus    uint   `json:"cpus"`    // number of physical CPUs
	Cores   uint   `json:"cores"`   // number of physical CPU cores
	Threads uint   `json:"threads"` // number of logical (HT) CPU cores
}

var (
	reTwoColumns = regexp.MustCompile("\t+: ")
	reExtraSpace = regexp.MustCompile(" +")
)

func (info *CPU) getCPUInfo() {
	info.Threads = uint(runtime.NumCPU())

	f, err := os.Open("/proc/cpuinfo")
	if err != nil {
		return
	}
	defer f.Close()

	cpu := make(map[string]bool)
	core := make(map[string]bool)

	var cpuID string

	s := bufio.NewScanner(f)
	for s.Scan() {
		if sl := reTwoColumns.Split(s.Text(), 2); sl != nil {
			switch sl[0] {
			case "physical id":
				cpuID = sl[1]
				cpu[cpuID] = true
			case "core id":
				coreID := fmt.Sprintf("%s/%s", cpuID, sl[1])
				core[coreID] = true
			case "vendor_id":
				if info.Vendor == "" {
					info.Vendor = sl[1]
				}
			case "model name":
				if info.Model == "" {
					// CPU model, as reported by /proc/cpuinfo, can be a bit ugly. Clean up...
					model := reExtraSpace.ReplaceAllLiteralString(sl[1], " ")
					info.Model = strings.Replace(model, "- ", "-", 1)
				}
			}
		}
	}
	if s.Err() != nil {
		return
	}

	info.Cpus = uint(len(cpu))
	info.Cores = uint(len(core))
}

func (i *CPU) YAMLString() string {
	return SafeYAML(i)
}

func (i *CPU) JSONString(indent bool) string {
	return SafeJSON(i, indent)
}
